import {createRouter, createWebHistory} from 'vue-router'
import Layout from '../layout/Layout.vue'
import {useAppStore} from "../store";
import { getMenuList } from '../api/system/menu.js'

// 动态生成路由的方法
function generateRoutes(menuData) {
    const dynamicRoutes = [];

    // 根据后端返回的菜单数据生成路由配置
    menuData.forEach(item => {
        if (item.children && item.children.length > 0) {
            // 处理有子菜单的情况
            item.children.forEach(subItem => {
                if (subItem.component) {
                    dynamicRoutes.push({
                        path: subItem.path,
                        component: () => import(`../${subItem.component}`),
                        meta: { title: subItem.menuName }
                    });
                }
            });
        } else {
            // 处理无子菜单的情况
            if (item.component) {
                dynamicRoutes.push({
                    path: item.path,
                    component: () => import(`../${item.component}`),
                    meta: { title: item.menuName }
                });
            }
        }
    });

    return dynamicRoutes;
}

// 基础路由（不需要权限的页面）
const constantRoutes = [
    {
        path: '/',
        component: Layout,
        redirect: 'index',
        children: [
            {
                path: 'index',
                component: () => import('../views/Welcome.vue'),
                meta: {title: 'Welcome'}
            },
            {
                path: '/dashboard',
                component: () => import('../views/Dashboard.vue'),
                meta: {title: 'Dashboard'}
            },
            {
                path: '/about',
                component: () => import('../views/About.vue'),
                meta: {title: 'About'}
            },
            {
                path: '/home',
                component: () => import('../views/Home.vue'),
                meta: {title: 'Home'}
            },
            {
                path: '/users',
                component: () => import('../views/Center.vue'),
                meta: {title: 'Users'}
            },
            {
                path: '/icons',
                component: () => import('../components/icons/EICons.vue'),
                meta: {title: 'ICons'}
            },
            {
                path: '/form',
                component: () => import('../components/form/Form.vue'),
                meta: {title: 'Form'}
            },
            {
                path: '/markdown',
                component: () => import('../components/markdown/Markdown.vue'),
                meta: {title: 'Markdown'}
            },
            {
                path: '/table',
                component: () => import('../components/table/Table.vue'),
                meta: {title: 'Table'}
            },
            {
                path: '/button',
                component: () => import('../components/base/EButton.vue'),
                meta: {title: 'Button'}
            },
            {
                path: '/guide',
                component: () => import('../components/guide/Guide.vue'),
                meta: {title: 'Guide'}
            },
            {
                path: '/dept',
                component: () => import('../components/tree/DeptTree.vue'),
                meta: {title: 'DeptTree'}
            },
            {
                path: '/adduser',
                component: () => import('../components/tree/AddUser.vue'),
                meta: {title: 'AddDeptUser'}
            },
            {
                path: '/progress',
                component: () => import('../components/progress/EProgress.vue'),
                meta: {title: 'Progress'}
            },
            {
                path: '/picture',
                component: () => import('../components/picture/PictureResize.vue'),
                meta: {title: 'PictureResize'}
            }
        ]
    },
    {
        path: '/login',
        component: () => import('../views/Login.vue')
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'error',
        redirect: '/error',
        children: [
            {
                path: '/error',
                component: () => import('../views/error/404.vue')
            }
        ]
    }
];

// 异步路由（需要根据权限动态添加）
export const asyncRoutes = [
    {
        path: '/',
        component: Layout,
        redirect: 'index',
        children: [
            {
                path: 'index',
                component: () => import('../views/Welcome.vue'),
                meta: {title: 'Welcome'}
            }
            // 其他固定子路由...
        ]
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes
});

// 注册一个全局前置守卫
/*router.beforeEach((to, from, next) => {
    const store = useAppStore();
    if (to.path === '/login' || to.path === '/error') {
        store.updateState({appIsReady: true, appIsRender: true, layout: false});
        next();
    } else {
        let token = localStorage.getItem('token');
        if (token === null || token === '') {
            next('/login');
        } else {
            store.updateState({appIsReady: true, appIsRender: true, layout: true});
            next();
        }
    }
})*/

// 动态添加路由的方法
export function setupDynamicRoutes(menuData) {
    const dynamicRoutes = generateRoutes(menuData);

    // 将动态路由添加到布局路由的children中
    const layoutRoute = asyncRoutes.find(route => route.path === '/');
    if (layoutRoute) {
        layoutRoute.children = [...layoutRoute.children, ...dynamicRoutes];
    }

    // 添加异步路由到路由器
    asyncRoutes.forEach(route => {
        router.addRoute(route);
    });
}


export default router;